<template>
  <div class="cangku-container">
    <!-- 顶部操作栏 -->
    <div class="header-section">
      <div class="toolbar-left">
      </div>
      
      <div class="toolbar-right">
        <el-button type="primary" @click="DK(null)" style="background-color: #ff4d4f; border-color: #ff4d4f;">
          新增
        </el-button>
        <!-- 修改导出按钮，使用el-button组件并绑定点击事件 -->
        <el-button type="default" @click="handleExport">
          导出
        </el-button>
        <el-button type="default" @click="handleBatchDelete" :disabled="selectedRows.length === 0">
          删除
        </el-button>
      </div>
    </div>

    <!-- 搜索区域 -->
    <div class="search-section">
      <div class="search-item">
        <label>编码：</label>
        <el-input v-model="searchForm.CangkuNo" placeholder="请输入编码" style="width: 200px" />
      </div>
      <div class="search-item">
        <label>名称：</label>
        <el-input v-model="searchForm.CangName" placeholder="请输入名称" style="width: 200px" />
      </div>
      <div class="search-item">
        <label>类型：</label>
        <el-input v-model="searchForm.CangTypeId" placeholder="请输入类型" style="width: 200px" />
      </div>
      <div class="search-item">
        <label>仓管员：</label>
        <!-- 将文本框改为下拉框 -->
        <el-select v-model="searchForm.Role" placeholder="请选择仓管员" style="width: 200px">
          <el-option value="" label="全部" />
          <el-option v-for="user in managerList" :key="user.userId" :label="user.userNickname" :value="user.userNickname" />
        </el-select>
      </div>
      <el-button type="primary" @click="getCangkuList" style="margin-left: 20px;">查询</el-button>
    </div>

    <!-- 表格区域 -->
    <div class="table-section">
      <el-table
        :data="cangkuList"
        style="width: 100%"
        border
        stripe
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" width="80" />
        <el-table-column prop="cangkuNo" label="编码" min-width="120" />
        <el-table-column prop="cangName" label="名称" min-width="150" />
        <el-table-column prop="cangTypeName" label="类型" width="120">
        </el-table-column>
        <el-table-column prop="role" label="仓管员" min-width="120" />
        <el-table-column prop="address" label="地址" min-width="150" />
        <el-table-column prop="mShu" label="描述" min-width="150" />
        <el-table-column prop="createName" label="创建人" min-width="180" />
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="scope">
            {{ scope.row.createTime ? moment(scope.row.createTime).format('YYYY-MM-DD') : '' }}
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="更新时间" width="180">
          <template #default="scope">
            {{ scope.row.updateTime ? moment(scope.row.updateTime).format('YYYY-MM-DD') : '' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button type="text" class="action-btn" @click="DK(row)" title="编辑">
              编辑
            </el-button>
            <el-button type="text" class="action-btn delete-btn" @click="handleDelete(row)" title="删除">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-section">
        <div class="pagination-info">共 {{ pagination.totalCount }} 条数据</div>
        <el-pagination
          v-model:current-page="pagination.pageIndex"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="prev, pager, next, sizes, jumper"
          :total="pagination.totalCount"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 新增/编辑弹窗 -->
    <el-dialog
      v-model="dialogVisible.is"
      :title="dialogVisible.title"
      width="600px"
      :before-close="handleDialogClose"
    >
      <el-form
        ref="cangkuFormRef"
        :model="formData"
        label-width="100px"
      >
        <el-form-item label="仓库编号" prop="cangid">
          <el-input v-model="formData.cangkuNo" placeholder="请输入仓库编号" />
        </el-form-item>
        <el-form-item label="仓库名称" prop="cangname">
          <el-input v-model="formData.cangName" placeholder="请输入仓库名称" />
        </el-form-item>
        <el-form-item label="仓库类型" prop="cangtypeid">
          <el-select v-model="formData.cangTypeId" placeholder="请选择仓库类型">
            <!-- 动态渲染仓库类型选项 -->
            <el-option 
              v-for="type in cangTypeList" 
              :label="type.cangTypeName" 
              :value="type.cangTypeId"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 在弹窗中修改仓管员输入框 -->
        <el-form-item label="仓管员" prop="createname">
          <el-input v-model="formData.role" placeholder="请选择数据" readonly style="width: 300px;" />
          <el-button type="primary" @click="showUserModal" style="margin-left: 10px; background-color: #ff4d4f; border-color: #ff4d4f;">
            选择
          </el-button>
        </el-form-item>
        
        <!-- 在主容器末尾添加用户选择弹窗 -->
        <el-dialog
          v-model="userModalVisible"
          title="选择数据"
          width="800px"
          :before-close="closeUserModal"
        >
          <!-- 用户列表 -->
          <el-table
            :data="userList"
            style="width: 100%"
            border
            @selection-change="handleUserSelectionChange"
            row-key="userId"
            ref="userTableRef"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column type="index" label="序号" width="80" />
            <el-table-column prop="userName" label="用户名" min-width="120" />
            <el-table-column prop="userNickname" label="昵称" min-width="150" />
            <el-table-column prop="oranCord" label="部门" min-width="180" />
          </el-table>
          
          <!-- 分页 -->
          <div style="margin-top: 15px; display: flex; justify-content: flex-end; align-items: center;">
            <el-pagination
              v-model:current-page="userPagination.pageIndex"
              v-model:page-size="userPagination.pageSize"
              :page-sizes="[10, 20, 50, 100]"
              layout="prev, pager, next, sizes, jumper, total"
              :total="userPagination.totalCount"
            />
          </div>
          
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="closeUserModal">取消</el-button>
              <el-button type="primary" @click="confirmUserSelection">确定</el-button>
            </span>
          </template>
        </el-dialog>
        <el-form-item label="地址" prop="address">
          <el-input v-model="formData.address" placeholder="请输入地址" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="formData.MShu" placeholder="请输入描述" type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleDialogClose">取消</el-button>
          <el-button type="primary" @click="handleSave">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { APIs } from '../../Http/http'
import moment from 'moment'
const cangkuList = ref<any[]>([])
// 仓库类型列表
const cangTypeList = ref<any[]>([])
// 分页数据
const pagination = reactive({
  pageIndex: 1,
  pageSize: 10,
  totalCount: 0
})

// 添加仓管员列表变量
const managerList = ref<any[]>([])

// 弹窗相关
const dialogVisible = reactive({
  title:"",
  is:false
})
const cangkuFormRef = ref()

// 搜索表单
const searchForm = reactive({
  CangkuNo: '',
  CangName: '',
  CangTypeId: '',
  Role: ''
})

// 选中的行数据
const selectedRows = ref<any[]>([])

// 表单数据
const formData = reactive({
  "cangName": "",
  cangkuNo:"",
  "cangTypeId": null,
  "role": "",
  "createName": "",
  address:"",
  MShu:""
})

// 初始加载数据
onMounted(() => {
  getCangkuList()
  getCangTypeList() // 添加获取仓库类型列表
  getManagerList() // 添加获取仓管员列表
})

const handleSelectionChange = (val: any[]) => {
  selectedRows.value = val;
  console.log(selectedRows.value);
};
const getSelectedRowsArray = () => {
  return selectedRows.value.map(row => ({
    id: row.cangId,
  }));
};

// 实现批量删除功能
const handleBatchDelete = () => {
  const selectedIds = getSelectedRowsArray();
  const requestData = {
    ids: selectedIds.map(item => item.id)
  };
  
  ElMessageBox.confirm(
    `确定要删除选中的${selectedRows.value.length}个车间吗？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    APIs.post("/api/Write/PLDeleCangKu", requestData).then(res=>{
      if(res.data.code==100) {
        ElMessage.success("批量删除成功");
       getCangkuList();
      }
    })
  });
};

const getCangkuList = async () => {
  const response = await APIs.get('/api/Read/ShowCangku', {
    params: {
      PageIndex: pagination.pageIndex,
      PageSize: pagination.pageSize,
      ...searchForm
    }
  })
  
  if (response.data.code === 100) {
    cangkuList.value = response.data.data.data
    pagination.totalCount = response.data.data.totalCount
  }
}


// 新增
const DK = (row:any) => { 
  dialogVisible.is = true
  if(row==null)
{
  dialogVisible.title="新增"
  formData.MShu="",
  formData.address="",
  formData.cangName="",
  formData.cangTypeId=null,
  formData.role="",
  formData.cangkuNo=""
}
else
{
  dialogVisible.title="编辑"
    Object.assign(formData, row)
}
}
const handleDelete = (row: any) => {
  ElMessageBox.confirm(`确定要删除仓库 "${row.cangName}" 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    APIs.post('/api/Write/DeleteCangku', row).then(() => {
      ElMessage.success('删除成功')
      getCangkuList()
    })
  })
}

// 批量删除

// 导出功能完善 - 修复文件下载问题
const handleExport = async () => {
   {
    
    // 使用axios发送GET请求，设置responseType为blob
    const response = await APIs.get('/api/Read/GetExcl', {
      responseType: 'blob',
    });

    const blob = new Blob([response.data], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    });
    
    // 获取文件名（从响应头或使用默认名）
    let fileName = '仓库数据.xlsx';
    const contentDisposition = response.headers['content-disposition'];
    if (contentDisposition) {
      const matches = /filename=([^;]+)/i.exec(contentDisposition);
      if (matches && matches[1]) {
        fileName = decodeURIComponent(matches[1].replace(/"/g, ''));
      }
    }
    
    // 创建下载链接
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = fileName;
    
    // 模拟点击下载
    document.body.appendChild(link);
    link.click();
    
    // 清理临时链接
    setTimeout(() => {
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
    }, 100);
    
    // 显示成功提示
    ElMessage.closeAll();
    ElMessage.success('导出成功');
    
  } 
}

// 保存表单
const handleSave = () => {
  if (!cangkuFormRef.value) return
  
  cangkuFormRef.value.validate().then(() => {
    const submitData = {
      ...formData,
    }
    
    if (dialogVisible.title=="编辑") {
      APIs.post('/api/Write/UpdateCangku', submitData).then(response => {
        if (response.data.code === 100) {
          ElMessage.success('更新成功')
          dialogVisible.is = false
          getCangkuList()
        } else {
          ElMessage.error('更新失败')
        }
      })
    } else {
      APIs.post('/api/Write/AddCangku', submitData).then(response => {
        if (response.data.code === 100) {
          ElMessage.success('新增成功')
          dialogVisible.is = false
          getCangkuList()
        } else {
          ElMessage.error(response.data.msg)
        }
      })
    }
  })
}

// 关闭弹窗
const handleDialogClose = () => {
  if (cangkuFormRef.value) {
    cangkuFormRef.value.resetFields()
  }
  dialogVisible.is = false
}

// 分页处理
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  getCangkuList()
}

const handleCurrentChange = (current: number) => {
  pagination.pageIndex = current
  getCangkuList()
}



// 获取仓库类型列表
const getCangTypeList =  () => {
   {
     APIs.get('/api/Read/GetAllCangType').then(res=>{
      cangTypeList.value = res.data.data
     })
  } 
}
// 在script部分添加用户选择相关变量
// 用户列表数据
const userList = ref<any[]>([])
// 用户分页数据
const userPagination = reactive({
  pageIndex: 1,
  pageSize: 10,
  totalCount: 0
})
// 用户弹窗可见性
const userModalVisible = ref(false)
// 用户表格引用
const userTableRef = ref()
// 选中的用户列表
const selectedUsers = ref<any[]>([])

// 显示用户选择弹窗
const showUserModal = () => {
  selectedUsers.value = []
  userPagination.pageIndex = 1
  getUserList() // 打开弹窗时加载用户数据
  userModalVisible.value = true
}

// 关闭用户选择弹窗
const closeUserModal = () => {
  userModalVisible.value = false
  // 清空选择状态
  if (userTableRef.value) {
    userTableRef.value.clearSelection()
  }
  selectedUsers.value = []
}

// 确认选择用户
const confirmUserSelection = () => {
  console.log('选中的用户:', selectedUsers.value)
  if (selectedUsers.value.length > 0) {
    // 如果允许多选，可以用逗号分隔多个昵称
    // 这里假设只允许选择一个用户
    formData.role = selectedUsers.value[0].userNickname // 设置仓管员名称
    // 保存用户ID（如果后端需要）
    // formData.userId = selectedUsers.value[0].userId
    ElMessage.success('已选择用户：' + selectedUsers.value[0].userNickname)
  } else {
    ElMessage.warning('请先选择一个用户')
    return
  }
  closeUserModal()
}

// 处理用户选择变化 - 这是关键的修复部分
const handleUserSelectionChange = (selection: any[]) => {
  console.log('选择变化:', selection)
  selectedUsers.value = selection
}

// 获取用户列表
const getUserList = async () => {
  {
    const response = await APIs.get('/api/Read/GetAccount', {
      params: {
        PageIndex: userPagination.pageIndex,
        PageSize: userPagination.pageSize
      }
    })
    if (response.data.code === 100) {
      userList.value = response.data.data.data
      userPagination.totalCount = response.data.data.totalCount
    }
  }
}
watch(userPagination,()=>{
  userList
})

// 获取仓管员列表
const getManagerList = async () => {
  try {
    const response = await APIs.get('/api/Read/GetAccount', {
      params: {
        PageIndex: 1,
        PageSize: 1000 // 获取足够多的用户数据用于下拉选择
      }
    })
    if (response.data.code === 100) {
      managerList.value = response.data.data.data
    }
  } catch (error) {
    console.error('获取仓管员列表失败:', error)
    ElMessage.error('获取仓管员列表失败')
  }
}
</script>

<style scoped>
.cangku-container {
  background: white;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.header-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background-color: #fafafa;
  border-bottom: 1px solid #e4e7ed;
}

.toolbar-left {
  display: flex;
  gap: 15px;
  align-items: center;
}

.toolbar-right {
  display: flex;
  gap: 10px;
}

.search-section {
  padding: 15px 20px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 15px;
}

.search-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.search-item label {
  white-space: nowrap;
}

.table-section {
  flex: 1;
  overflow: auto;
  padding: 20px;
}

.pagination-section {
  margin-top: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-info {
  color: #606266;
}

:deep(.el-table .el-table__fixed-right) {
  height: 100% !important;
}

.action-btn {
  color: #ff4d4f;
}

.delete-btn {
  color: #ff4d4f;
}
</style>